package cn.walls1717.wallsmall.search.service.impl;

import cn.hutool.json.JSONUtil;
import cn.walls1717.wallsmall.common.pojo.to.es.SkuEsModel;
import cn.walls1717.wallsmall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static cn.walls1717.wallsmall.search.config.ESConfig.COMMON_OPTIONS;
import static cn.walls1717.wallsmall.search.constant.EsConstant.PRODUCT_INDEX;

/**
 * @author walls1717
 * @since 2022/11/02 14:47
 **/
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 保存上架商品的信息
     *
     * @param skuEsModels sku数据模型
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String skuJson = JSONUtil.toJsonStr(skuEsModel);
            indexRequest.source(skuJson, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, COMMON_OPTIONS);
        boolean flag = bulk.hasFailures();
        if (flag) {
            List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("商品上架错误 -> {}", collect);
        }
        return !flag;
    }
}
